#include <string.h>
#include "CifDataLoaderByLine.h"

CifDataLoaderByLine::CifDataLoaderByLine()
{
	currentLine = -1;
	currentChar = ' ';
	currentColumn = -1;
	currentLineLength = -1;
}

CifDataLoaderByLine::~CifDataLoaderByLine()
{
}


void CifDataLoaderByLine::Parse()
{
	while (!IsEof())
	{
		ReadLine();

		while (!IsEndOfLine())
		{
			ReadChar();
		}
	}
}

int CifDataLoaderByLine::IsEndOfLine()
{
	if (currentColumn >= currentLineLength)
	{
		return 1;
	}

	return 0;
}

void CifDataLoaderByLine::ReadLine()
{
	char *str = fgets(readBuffer, CIF_MAX_LINE_LENGTH, cifFile);

	if (str == NULL)
	{
		if (ferror(cifFile))
		{
			errorCode = CIF_ERROR_CODE_INTERNAL_ERROR;
		}

		return;
	}

	currentChar = ' ';
	currentColumn = -1;
	currentLine++;
	currentLineLength = strlen(readBuffer);

	/* Remove end of line characters from the end of the buffer. */
	if (currentLineLength > 0)
	{
		char lastChar = readBuffer[currentLineLength - 1];

		while ((lastChar == 10 || lastChar == 13) && currentLineLength > 0)
		{
			--currentLineLength;
		}
	}
}

char CifDataLoaderByLine::ReadChar()
{
	if (currentColumn >= currentLineLength)
	{
		errorCode = CIF_ERROR_CODE_INTERNAL_ERROR;
		return ' ';
	}

	currentColumn++;
	currentChar = readBuffer[currentColumn];

	return currentChar;
}